package me.ezjs.framework.core.model;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * 用于DAOFilter中存储查询条件.
 * Created by zero-mac on 16/3/10.
 */
public class ParamTree {

    private ParamNode rootNode;//根节点

    public ParamTree() {
        //默认根节点为and连接
        rootNode = new ParamNode(ParamNode.Relation.and);
    }

    public ParamTree(ParamNode.Relation relation) {
        rootNode = new ParamNode(relation);
    }

    /**
     * 把条件添加到根节点之下
     *
     * @param nodes
     * @return 返回父子节点
     */
    public ParamNode addNodes(ParamNode... nodes) {
        return add2Node(rootNode, nodes);
    }

    /**
     * 将节点添加到指定节点之下
     *
     * @param father
     * @param child
     * @return
     */
    public ParamNode add2Node(ParamNode father, ParamNode... child) {
        father.addNodes(child);
        return father;
    }

    public ParamNode addParameter(Parameter pm) {
        ParamNode node = new ParamNode(pm);
        return addNodes(node);
    }

    /**
     * 设置跟节点为or查询
     */
    public void useOrRelation4Root() {
        rootNode.setRelation(ParamNode.Relation.or);
    }

    public ParamNode getRootNode() {
        return rootNode;
    }

    private void toString(StringBuilder sb, ParamNode node) {
        sb.append("{");
        if (node.getRelation() != null) {
            sb.append("relation: " + node.getRelation() + ", ");
        }
        if (node.getNodes() != null) {
            sb.append("nodes: [");
            for (ParamNode pn :
                    node.getNodes()) {
                toString(sb, pn);
            }
            sb.append("], ");
        }
        if (node.getParameter() != null) {
            sb.append("param: " + node.getParameter().toString() + ", ");
        }

        sb.append("} ,");
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        toString(sb, rootNode);
        return sb.toString();
    }
}
